# -*- coding:utf-8 -*-
from twisted.protocols.basic import LineReceiver
import pickle
import sys
import os

reload(sys)
sys.setdefaultencoding('utf-8')
import os
from API import log, my_size, MyTimer


class Status:
    RECV = 'RECV'  # 接受文件状态
    SEND = 'SEND'  # 发送文件状态
    DONE = 'DONE'  # 当前文件传输完成
    WAIT = 'WAIT'  # 等待对方响应)
    LOOP = 'LOOP'  # 循环发送字节流
    FIND = 'FIND'


class FileTranClientProtocol(LineReceiver):
    def __init__(self, serverpath, localpath):
        self.fp = None
        self.mystatus = None
        self.yourstatus = None
        self.timer = MyTimer()
        self.localpath = localpath
        self.serverpath = serverpath
        self.cur_size = 0
        self.total_size = 0



        # 根据命令行 查找对应的命令

    def lineReceived(self, line):
        arr = line.split(':')
        cmd = line[0:4]
        param = pickle.loads(line[4:])
        func = getattr(self, 'do_' + cmd)
        func(param)

    def dataReceived(self, data):
        # 我处在接受文件 状态 对方处在发送文件状态
        if self.mystatus == Status.LOOP:
            self.cur_size += len(data)
            self.fp.write(data)
            tmp = self.timer.get(self.cur_size, self.total_size)
            if tmp:
                print tmp
        else:
            # 处理命令行
            LineReceiver.dataReceived(self, data)

    def Run(self):
        self.fp = open(self.localpath, 'wb')
        self.sendLine('STOR' + pickle.dumps(self.serverpath))
        self.STAT(Status.WAIT)

        # 告诉对方 我的状态

    def do_WAIT(self, param):
        try:
            fsize = int(param)
            if fsize:
                self.total_size = fsize
                self.STAT(Status.RECV)
            else:
                raise ValueError
        except ValueError:
            print 'No File!'
            self.connectionLost("ERROR")

    def STAT(self, status):
        print 'tell other ' + status
        self.mystatus = status
        self.sendLine('STAT' + pickle.dumps(status))

    def do_STAT(self, param):
        print 'tell me ' + param
        self.yourstatus = param
        # 告诉发送端开始文件流循环
        if self.yourstatus == Status.SEND and self.mystatus == Status.RECV:
            self.STAT(Status.LOOP)

    def connectionMade(self):
        self.Run()

    def connectionLost(self, reason):
        if self.fp: self.fp.close()
        print my_size(self.total_size)
        log.write("finish")


class FileTranUploadProtocol(LineReceiver):
    blocksize = 65536

    def __init__(self, serverpath, localpath):
        self.fp = None
        self.mystatus = None
        self.yourstatus = None
        self.localpath = localpath
        self.serverpath = serverpath
        self.total = 0
        self.timer = MyTimer()
        self.fsize = os.path.getsize(self.fp)

        # 根据命令行 查找对应的命令

    def lineReceived(self, line):
        arr = line.split(':')
        cmd = line[0:4]
        param = pickle.loads(line[4:])
        func = getattr(self, 'do_' + cmd)
        func(param)

    def dataReceived(self, data):
        LineReceiver.dataReceived(self, data)

    def Run(self):
        self.fp = open(self.localpath, 'rb')
        self.sendLine('FIND' + pickle.dumps(self.serverpath))
        self.STAT(Status.SEND)

        # 告诉对方 我的状态

    def STAT(self, status):
        print 'tell other ' + status
        self.mystatus = status
        self.sendLine('STAT' + pickle.dumps(status))

    def do_STAT(self, param):
        print 'tell me ' + param
        self.yourstatus = param
        # 告诉发送端开始文件流循环
        if self.yourstatus == Status.LOOP and self.mystatus == Status.SEND:
            while 1:
                buf = self.fp.read(self.blocksize)
                if not buf: break
                self.transport.write(buf)
            self.transport.loseConnection()

    def connectionMade(self):
        print "Connect success!"
        self.Run()

    def connectionLost(self, reason):
        if self.fp: self.fp.close()
        log.write("OK!" + str(self.total))
        try:
            os._exit(0)
        except SystemExit, error:
            pass


import json


class CCP(LineReceiver):
    def __init__(self,content):
        self.content = content

    def lineReceived(self, line):
        print json.loads(line)

    def dataReceived(self, data):
        LineReceiver.dataReceived(self, data)

    def Run(self):
        tmp = json.dumps(self.content)
        self.sendLine(tmp)

    def connectionMade(self):
        print "Connect success!"
        self.Run()

    def connectionLost(self, reason):
        try:
            os._exit(0)
        except SystemExit, error:
            pass
